package com.yun.util.listen;


import com.alibaba.excel.annotation.ExcelProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 导入导出中心    用的条件：1把导出的类对象创建并注册到bean，2.类对象添加自定义注解 ExcelInit.class  3.属性上面使用ExcelProperty注解
 */
public class ImportReportCenter {

    static final Logger logger = LoggerFactory.getLogger(ImportReportCenter.class);

    //key: classname   value:类对象.... 属性值
    private static final Map<String, Map<Class<?>, List<ExcelProperty>>> ExcelPropertyCacheMap = new HashMap<>();

    private static ApplicationContext context;

    public static void initExcelProperty(ApplicationContext applicationContext){
        context = applicationContext;
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(ExcelInit.class);
        for (String key : beans.keySet()) {
            columnInfo(beans.get(key));
        }
        logger.info("初始化导入导出中心完毕");
    }

    private static void columnInfo(Object newInstance){
        Class<?> aClass = newInstance.getClass();
        Field[] fields = aClass.getDeclaredFields();
        Map<Class<?>, List<ExcelProperty>> map = new HashMap<>();
        List<ExcelProperty> list = new ArrayList<>();
        for (Field field : fields) {
            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation!=null){
                list.add(annotation);
            }
        }
        map.put(aClass,list);
        ExcelPropertyCacheMap.put(aClass.getSimpleName(),map);
    }


    public static Map<Class<?>, List<ExcelProperty>> getEntity(String classname){
        return ExcelPropertyCacheMap.get(classname);
    }

    public static ApplicationContext getContext(){
        return context;
    }
}
